package com.intexh.quickandroid.module.mine;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.intexh.quickandroid.R;
import com.intexh.quickandroid.base.BaseActivity;
import com.intexh.quickandroid.helper.UserHelper;
import com.intexh.quickandroid.module.chat.ChatManager.EasemobUtil;
import com.intexh.quickandroid.module.chat.bean.ChatMessage;
import com.intexh.quickandroid.module.chat.bean.ChatSession;
import com.intexh.quickandroid.module.chat.event.UpdateChatMessageEvent;
import com.intexh.quickandroid.module.chat.ui.AppChatActivity;
import com.intexh.quickandroid.module.chat.util.DateUtil;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.ValidateUtils;
import com.intexh.quickandroid.utils.glide.GlideHelper;
import com.intexh.quickandroid.widget.easyadapter.BaseViewHolder;
import com.intexh.quickandroid.widget.easyadapter.RecyclerArrayAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MessageActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.system_message_tv)
    TextView systemMessageTv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private RecyclerArrayAdapter<ChatSession> mAdapter;
    private List<ChatSession> allChatSessions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initRecyclerView();
        getChatHistory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdateChatMessageEvent event) {
        //刷新聊天记录列表
        getChatHistory();
    }

    private void getChatHistory() {
        mAdapter.clear();
        allChatSessions = EasemobUtil.INSTANCE.getAllChatSessions();
        mAdapter.addAll(allChatSessions);
    }
    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter = new RecyclerArrayAdapter<ChatSession>(mContext){

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_message,parent,false));
            }

            class ViewHolder extends BaseViewHolder<ChatSession>{
                private ImageView ivImage,point_iv;
                private TextView tvName;
                private TextView tvNewestMessage;
                private TextView tvTime;
                private TextView tvDelete;
                private RelativeLayout itemLayout;
                private View line;
                public ViewHolder(View itemView) {
                    super(itemView);
                    ivImage =  itemView.findViewById(R.id.item_friend_chat_img);
                    tvName =  itemView.findViewById(R.id.item_friend_name);
                    point_iv =  itemView.findViewById(R.id.point_iv);
                    tvNewestMessage =  itemView.findViewById(R.id.item_friend_newest_message);
                    tvTime =  itemView.findViewById(R.id.item_friend_message_time);
                    tvDelete =  itemView.findViewById(R.id.item_delete_btn);
                    itemLayout =  itemView.findViewById(R.id.item_friend_layout);
                    line = itemView.findViewById(R.id.item_friend_line);
                }

                @Override
                public void setData(ChatSession data) {
                    tvDelete.setOnClickListener(v -> {
                        allChatSessions.get(getDataPosition()).delete();
                        remove(getAllData().get(getDataPosition()));
//                        //删除聊天消息
//                        List<ChatMessage> all = ChatMessage.getAll(allChatSessions.get(getDataPosition()).getSessionId());
//                        for(int i = 0 ; i < all.size() ; i++) {
//                            all.get(i).deleteAsync();
//                        }
                    });
                    itemLayout.setOnClickListener(v -> {
                        EventBus.getDefault().post(new UpdateChatMessageEvent(2));  //点击发送消息更新首页
                        ChatSession.update(data.getSessionId());
                        point_iv.setVisibility(View.GONE);
                        if(data.getIsGroup()){
                            AppChatActivity.startGroupActivity(mContext,data.getGroup_id(),data.getSessionId(),data.getGroup_name(),data.getGroup_avatar());
                        }else{
                            AppChatActivity.startActivity(mContext,data.getUid(),data.getSessionId(),data.getAvatar(),data.getName());
                        }

                    });
                    //分割线
                    if(getAdapterPosition() == 0) {
                        line.setVisibility(View.GONE);
                    }else {
                        line.setVisibility(View.VISIBLE);
                    }
                    if(data.getIsGroup()){
                        GlideHelper.INSTANCE.loadImage(ivImage,data.getGroup_avatar(),5);
                        tvName.setText(data.getGroup_name());
                    }else{
                        GlideHelper.INSTANCE.loadImage(ivImage,data.getAvatar(),5);
                        tvName.setText(data.getName());
                    }

                    String lastMessage = data.getLastMessage();
                    ChatMessage chatMessage = GsonUtils.jsonToBean(lastMessage, ChatMessage.class);
                    if (ValidateUtils.isValidate(chatMessage)) {
                        String u = UserHelper.getUser().getUserid().equals(chatMessage.getUid())?"出":"来";
                        if (chatMessage.getType() == 1) {
                            tvNewestMessage.setText(chatMessage.getContent());
                        } else if (chatMessage.getType() == 2) {
                            tvNewestMessage.setText("[发"+u+"一张图片]");
                        } else if (chatMessage.getType() == 7) {
                            tvNewestMessage.setText("[发"+u+"一段语音]");
                        }
                    }
                    if (data.getNotReadCount() > 0) {
                        point_iv.setVisibility(View.VISIBLE);
                    } else {
                        point_iv.setVisibility(View.GONE);
                    }
                    tvTime.setText(DateUtil.postTime(data.getCreateTime()));
                }

            }
        });
    }


    @OnClick({R.id.back_iv, R.id.system_message_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.system_message_tv:
                break;
        }
    }
}
